package com.sise.thread.Lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 作者：idea
 * 日期：2018/6/25
 * 描述：锁响应中断
 */
public class LockInterruptibly {
    private Lock lock=new ReentrantLock();


    public void insert(Thread thread) throws InterruptedException {
        lock.lockInterruptibly(); //注意，如果需要正确中断等待锁的线程，必须将获取锁放在外面，然后将InterruptedException抛出
        try {
            System.out.println(thread.getName()+"得到了锁！");
            long beginTime=System.currentTimeMillis();
            for(;;){
                if(System.currentTimeMillis()-beginTime>2000){
                    break;
                }
            }
            System.out.println("释放了锁");
        }catch (Exception e){

        }finally {
            System.out.println(thread.getName()+"开始执行finally操作！");
            lock.unlock();
            System.out.println(thread.getName()+"已经释放了锁操作");
        }
    }

    static class Mythread extends Thread{
        private LockInterruptibly test=null;
        public Mythread(LockInterruptibly lock){
            this.test=lock;
        }

        public void run(){
            try {
                test.insert(Thread.currentThread());
            } catch (InterruptedException e) {
                System.out.println(Thread.currentThread().getName()+"被中断了");
            }
        }

    }

    public static void main(String[] args) {
        LockInterruptibly lock=new LockInterruptibly();
        Thread thread1=new Mythread(lock);
        Thread thread2=new Mythread(lock);
        thread1.start();
        thread2.start();
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        thread2.interrupt();
    }

}
